import React, { useEffect, useState } from 'react'
import { Descriptions, PageHeader } from 'antd';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import moment from 'moment';
import { HeartOutlined, HeartFilled } from '@ant-design/icons';

export default function Detail() {
  const { id } = useParams();
  const [detail, setDetail] = useState();
  const [starType, setStarType] = useState(0);
  useEffect(()=>{
    axios({
      url:`/news/${id}?_expand=category&_expand=role`
    }).then(res =>{
      console.log(res.data);
      setDetail({...res.data, view:res.data.view + 1});
      return res;
    }).then(res =>
      axios.patch(`/news/${id}`,{view:res.data.view + 1}));
  },[id]);

  const handleStar = ()=>{
    setStarType(1);
    setDetail({...detail, star: detail.star + 1});
    axios.patch(`/news/${id}`,{star:detail.star + 1});
  }

  return (
    <div className="site-page-header-ghost-wrapper">
      {
        detail && 
        <div>
          <PageHeader
            ghost={false}
            onBack={() => window.history.back()}
            title={detail.title}
            subTitle={<div>{detail.category.title} {starType===0? <HeartOutlined onClick={()=>{
              handleStar();
            }}/>:<HeartFilled onClick={()=>{
              setStarType(0);
              setDetail({...detail, star: detail.star - 1});
            }}/>}</div>}
          >
            <Descriptions size="small" column={3}>
              <Descriptions.Item label="创建者">{detail.author}</Descriptions.Item>
              <Descriptions.Item label="发布时间">{detail.publishTime?moment(detail.createTime).format('YYYY-MM-DD HH:mm:ss'):'-'}</Descriptions.Item>
              <Descriptions.Item label="区域">{detail.region}</Descriptions.Item>
              <Descriptions.Item label="访问数量">{detail.view}</Descriptions.Item>
              <Descriptions.Item label="点赞数量">{detail.star}</Descriptions.Item>
              <Descriptions.Item label="评论数量">0</Descriptions.Item>
            </Descriptions>
          </PageHeader>
          <div dangerouslySetInnerHTML={{__html:detail.content}} style={{margin:'0 1.5rem', padding:'1rem',border:'1px solid grey', borderRadius:'.3rem', overflow:'auto', width:'95%', height:'43.75rem'}}/>
        </div>
      }
    </div>
  )
}
